<script lang="ts" setup>
import { ref, watch } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message, Tabs, Tree } from 'ant-design-vue';

import { useVbenForm } from '#/adapter';
import { getPermissionTree, type RoleSaveDto, saveRole } from '#/api/core/role';
import { $t } from '#/locales';

defineOptions({
  name: 'FormDrawer',
});

// 定义 props 参数，用于接收父组件传递的事件处理函数
const props = defineProps<{
  onSave: () => void;
}>();

const activeTab = ref('basic');
const treeData = ref<any[]>([]);
const checkedKeys = ref<(number | string)[]>([]);
const loading = ref(false);

// 加载权限树数据
async function loadPermissionTree(roleId?: number | string) {
  try {
    loading.value = true;
    const res = await getPermissionTree(roleId);
    if (res) {
      // 处理树数据，转换 title
      const processTreeNode = (nodes: any[]): any[] => {
        return nodes.map((node) => ({
          key: node.id,
          title: $t(node.title),
          id: node.id,
          checked: node.checked,
          children: node.children ? processTreeNode(node.children) : [],
        }));
      };
      treeData.value = processTreeNode(res);

      // 提取选中的节点ID
      if (roleId) {
        const selectedKeys: number[] = [];
        const extractCheckedKeys = (nodes: any[]) => {
          nodes.forEach((node) => {
            if (node.checked) {
              selectedKeys.push(node.id);
            }
            if (node.children) {
              extractCheckedKeys(node.children);
            }
          });
        };
        extractCheckedKeys(res);
        checkedKeys.value = selectedKeys;
      }
    }
  } catch (error: any) {
    message.error(error.message || $t('role.drawer.permission.loadFailed'));
  } finally {
    loading.value = false;
  }
}

const [Form, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        type: 'hidden', // 定义隐藏字段
      },
      fieldName: 'id',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('role.drawer.form.name.placeholder'),
      },
      fieldName: 'name',
      label: $t('role.drawer.form.name.label'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('role.drawer.form.description.placeholder'),
      },
      fieldName: 'description',
      label: $t('role.drawer.form.description.label'),
      rules: 'required',
    },
  ],
  showDefaultActions: false,
});

async function onSubmit(values: Record<string, any>) {
  try {
    const saveData: RoleSaveDto = {
      role: {
        name: values.name,
        description: values.description,
      },
      permissionIds: checkedKeys.value.map(Number),
    };

    if (values.id) {
      (saveData.role as { id: number }).id = Number(values.id);
    }

    await saveRole(saveData);
  } catch (error: any) {
    throw new Error(error.message || '提交失败');
  }
}

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    const isValid = await formApi.validate();
    if (isValid.valid) {
      try {
        const values = formApi.form.values;
        await formApi.submitForm();
        drawerApi.close();
        message.success(
          values.id
            ? $t('role.drawer.editSuccess')
            : $t('role.drawer.addSuccess'),
        );
        props.onSave();
      } catch (error: any) {
        message.error(
          $t('role.drawer.failed', {
            message: error.message || $t('common.submit.failed'),
          }),
        );
      }
    } else {
      message.error($t('common.form.required'));
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values = drawerApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values);
      }
      // 重置为基本信息标签页
      activeTab.value = 'basic';
    } else {
      // 关闭时清空数据
      treeData.value = [];
      checkedKeys.value = [];
    }
  },
});

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'permission' && treeData.value.length === 0) {
    const values = drawerApi.getData<Record<string, any>>();
    loadPermissionTree(values?.id);
  }
});
</script>
<template>
  <Drawer
    :title="$t('role.drawer.title.add')"
    :title-tooltip="$t('role.drawer.title.tooltip')"
  >
    <Tabs v-model:active-key="activeTab">
      <Tabs.TabPane key="basic" :tab="$t('role.drawer.tabs.basic')">
        <Form />
      </Tabs.TabPane>
      <Tabs.TabPane key="permission" :tab="$t('role.drawer.tabs.permission')">
        <div class="p-4">
          <div v-if="loading" class="py-4 text-center">
            {{ $t('role.drawer.permission.loading') }}
          </div>
          <Tree
            v-else
            v-model:checked-keys="checkedKeys"
            :default-expand-all="true"
            :field-names="{
              key: 'key',
              title: 'title',
              children: 'children',
            }"
            :selectable="false"
            :tree-data="treeData"
            checkable
            class="permission-tree"
          />
        </div>
      </Tabs.TabPane>
    </Tabs>
  </Drawer>
</template>

<style scoped>
.permission-tree {
  width: 100%;
  min-height: 300px;
}
</style>
